package com.qianguo.buyer.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.eva.androidlibrary.image.ImageHelper;
import com.eva.androidlibrary.utils.FileUtil;
import com.eva.androidlibrary.utils.UIUtil;
import com.eva.androidlibrary.utils.crop.Crop;
import com.qianguo.buyer.R;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 选择照片基类Activity
 *
 * @author GUXIA318
 * @date 2015-10-20 14:21
 */
public abstract class BaseChooseImageActivity extends BaseTitleActivity {

    public interface PicPickerCallback {
        void afterPick(String filePath);
    }

    public interface PicCropCallback {
        void afterCrop(File file);
    }

    protected static final int DEFAULT_MAX_AVATAR_SIZE = 400;

    /**
     * 相册选择
     */
    private static final int REQUEST_CODE_ALBUM = 1;

    /**
     * 拍照
     */
    private static final int REQUEST_CODE_CAMERA = 2;

    /**
     * 拍照文件名
     */
    private static final String TEMP_IMAGE_NAME = "temp.jpg";

    /**
     * 拍照存储路径
     */
    private String mCameraStoragePath;

    private String mCameraStorageFilePath;

    private PicPickerCallback mPicPickerCallback;
    private PicCropCallback mPicCropCallback;

    /**
     * 选择修改头像的方式对话框
     */
    public void showPickerDialog(PicPickerCallback callback) {
        mPicPickerCallback = callback;
        if (TextUtils.isEmpty(mCameraStoragePath)) {
            mCameraStoragePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
        }

        showDialog(this, getString(R.string.picture),
                getString(R.string.choose_picture_message),
                getString(R.string.album),
                getString(R.string.take_photo),
                new View.OnClickListener() {
                    // 从相册选择
                    @Override
                    public void onClick(View v) {
                        pickFromAlbum(REQUEST_CODE_ALBUM);
                        closeDialog();
                    }
                },
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickFromTakePhoto(REQUEST_CODE_CAMERA, mCameraStoragePath, TEMP_IMAGE_NAME);
                        closeDialog();
                    }
                });
    }

    /**
     * 相册选择照片
     *
     * @param requestCode
     */
    public void pickFromAlbum(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    /**
     * 拍照获取照片
     *
     * @param requestCode
     * @param filePath
     */
    public void pickFromTakePhoto(int requestCode, String filePath, String fileName) {
        /**
         * 调用快速拍照功能，查看you_sdk_path/docs/guide/topics/media/camera.html
         */
        if (!TextUtils.isEmpty(filePath)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 下面这句指定调用相机拍照后的照片存储的路径
            mCameraStorageFilePath = filePath + File.separator + fileName;
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraStorageFilePath)));
            startActivityForResult(intent, requestCode);
        } else {
            Toast.makeText(this, "照片存储路径不存在，无法使用拍照", Toast.LENGTH_SHORT);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ALBUM:
                    if (data != null && data.getData() != null) {
                        Uri uri = data.getData();
                        String path = FileUtil.getFilePath(this, uri);
                        rotateBitmap(path);
                    }
                    break;
                case REQUEST_CODE_CAMERA:
                    rotateBitmap(mCameraStorageFilePath);
                    break;
                case Crop.REQUEST_CROP:
                    handleCrop(data);
                    break;
            }
        }
    }

    private void handleCrop(Intent result) {
        Uri uri = Crop.getOutput(result);
        try {
            if (mPicCropCallback != null) {
                mPicCropCallback.afterCrop(new File(new URI(uri.toString())));
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片的旋转角度
     *
     * @param path 图片的绝对路径
     * @return 图片的旋转角度
     */
    private int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    private void rotateBitmap(String filePath) {
        Bitmap result = null;
        Bitmap source = null;
        File file = null;
        int degree = getBitmapDegree(filePath);
        if (degree != 0) {
            ImageHelper imageHelper = ImageHelper.getInstance(this);
            try {
                int size = UIUtil.getWindowWidth(this);
                source = imageHelper.getImage(filePath, size, size);
                // 根据旋转角度，生成旋转矩阵
                Matrix matrix = new Matrix();
                matrix.postRotate(degree);
                result = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
                file = imageHelper.saveBitmap(this, result, null, filePath, Bitmap.CompressFormat.JPEG);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (source != null) {
                    source.recycle();
                }

                if (result != null) {
                    result.recycle();
                }
            }
        }

        if (mPicPickerCallback != null) {
            if (file != null) {
                mPicPickerCallback.afterPick(file.getAbsolutePath());
            } else {
                mPicPickerCallback.afterPick(filePath);
            }
        }

    }

    /**
     * 剪裁图片
     *
     * @param filePath
     */
    public void crop(String filePath, PicCropCallback callback) {
        crop(new File(filePath), callback);
    }

    /**
     * 剪裁图片
     *
     * @param file
     *            图片file文件
     */
    public void crop(File file, PicCropCallback callback) {
        cropAsSquare(file, DEFAULT_MAX_AVATAR_SIZE, DEFAULT_MAX_AVATAR_SIZE, callback);
    }

    /**
     * 剪裁图片为正方形
     *
     * @param file
     * @param maxWidth
     * @param maxHeight
     */
    public void cropAsSquare(File file, int maxWidth, int maxHeight, PicCropCallback callback) {
        mPicCropCallback = callback;
        Uri outputUri = Uri.fromFile(new File(getCacheDir(), "cropped"));
        new Crop(Uri.fromFile(file)).output(outputUri).asSquare().withMaxSize(maxWidth, maxHeight).start(this);
    }

    /**
     * 剪裁图片为矩形
     *
     * @param file
     *            图片file文件
     */
    public void cropAsRectangle(File file, int aspectX, int aspectY, int maxWidth, int maxHeight) {
        Uri outputUri = Uri.fromFile(new File(getCacheDir(), "cropped"));
        new Crop(Uri.fromFile(file)).output(outputUri).withAspect(aspectX, aspectY).withMaxSize(maxWidth, maxHeight).start(this);
    }
}
